/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.eclass.servlet.front;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;

import cn.eclass.entity.SchoolEntity;
import cn.eclass.entity.SchoolOrderEntity;
import cn.eclass.servlet.ActionFace;
import cn.eclass.utils.ConstantsConf;
import cn.eclass.utils.Helper;

import com.google.gson.Gson;

/**
 *
 * @author fortruth
 */
public class Usubmit extends ActionFace {
    /*
     * "action":"create", "pswQuestion":pswQuestion, "pswAnswer":pswAnswer,
     * "schoolName":schoolName, "userName":userName, "orderNo":orderNo,
     * "orderAmount":orderAmount
     */

    private Map<String, Object> form2Entity(boolean update) throws Exception {
        String schoolId = request.getParameter("schoolId");
        String userName = request.getParameter("userName");
        String orderNo = request.getParameter("orderNo");
        String orderAmount = request.getParameter("orderAmount");
        String className = request.getParameter("className");

        className = Helper.toUTF8(className);
        String msg = null;
        Map<String, Object> result = new HashMap<String, Object>();

        float orderAmount_float = 0;
        int schoolId_int = 0;
        try {
            orderAmount_float = Float.parseFloat(orderAmount);
            schoolId_int = Integer.parseInt(schoolId);
        } catch (Exception e) {
            msg = ConstantsConf.formatError;
            result.put("msg", msg);
            return result;
        }
        SchoolOrderEntity soEnt;
        if (update) {
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            soEnt = beanFactory.getSchoolOrderBean().get(orderId);
        } else {
            soEnt = new SchoolOrderEntity();
        }
//		soEnt = new SchoolOrderEntity();
        soEnt.setClaimAmount(orderAmount_float);
        soEnt.setSchoolId(schoolId_int);
        soEnt.setUserId(user.getId());
        soEnt.setClassName(className);
        soEnt.setUserName(userName);
        soEnt.setOrderNo(orderNo);

        result.put("order", soEnt);

        return result;
    }

    public void doUpdate() {
        Map<String, Object> map = null;
        Map result = new HashMap();
        try {
            map = form2Entity(true);
        } catch (Exception e) {
            result.put("status", "failed");
            result.put("msg", ConstantsConf.sysError);
            out.print(new Gson().toJson(result));
            return;
        }
        SchoolOrderEntity soe = (SchoolOrderEntity) map.get("order");
        if (soe != null) {
            boolean success = beanFactory.getSchoolOrderBean().update(soe);
            if (success) {
                result.put("status", "success");
                session.removeAttribute(ConstantsConf.SCHOOLORDERLIST);
                out.print(new Gson().toJson(result));
            } else {
                result.put("status", "failed");
                result.put("msg", ConstantsConf.sysError);
                out.print(new Gson().toJson(result));
                return;
            }
        } else {
            result.put("status", "failed");
            result.put("msg", (String) map.get("msg"));
            out.print(new Gson().toJson(result));
            return;
        }
    }

    public void doCreate() {
        Map result = new HashMap();
		String pswQuestion = request.getParameter("pswQuestion");
		String pswAnswer = request.getParameter("pswAnswer");
        String oriPwdAnswer = user.getPwdAnswer();
        if (oriPwdAnswer == null || oriPwdAnswer.length() == 0) {
            if (pswAnswer == null || pswAnswer.length() == 0) {
                result.put("status", "failed");
                result.put("msg", ConstantsConf.noCorrectPswAnswer);
                out.print(new Gson().toJson(result));
                return;
            }
			pswQuestion = Helper.toUTF8(pswQuestion);
			pswAnswer = Helper.toUTF8(pswAnswer);
            user.setPwdAnswer(pswAnswer);
            user.setPwdQuestion(pswQuestion);
            beanFactory.getUserBean().update(user);
        }

        Map<String, Object> map = null;
        try {
            map = form2Entity(false);
        } catch (Exception e) {
            result.put("status", "failed");
            result.put("msg", ConstantsConf.sysError);
            out.print(new Gson().toJson(result));
            return;
        }
        SchoolOrderEntity soe = (SchoolOrderEntity) map.get("order");
        if (soe == null) {
            result.put("status", "failed");
            result.put("msg", (String) map.get("msg"));
            out.print(new Gson().toJson(result));
            return;
        }

        SchoolOrderEntity res = beanFactory.getSchoolOrderBean().add(soe);
        if (res == null) {
            result.put("status", "failed");
            result.put("msg", ConstantsConf.sysError);
            out.print(new Gson().toJson(result));
            return;
        }

        result.put("status", "success");
        session.removeAttribute(ConstantsConf.SCHOOLORDERLIST);
        out.print(new Gson().toJson(result));
    }

    private void checkLogIn() throws ServletException, IOException {
        if (user != null) {
            return;
        }

        request.setAttribute("redirect", "usubmit");
        request.getRequestDispatcher(logInView).forward(request, response);
    }

    public void doModify() {
        try {
            checkLogIn();
            int orderId = Integer.parseInt(request.getParameter("orderId"));

            SchoolOrderEntity soe = beanFactory.getSchoolOrderBean().get(orderId);
            request.setAttribute("order", soe);
            request.setAttribute("modify", "true");
            List<SchoolEntity> schoolList = beanFactory.getSchoolBean().list();
            request.setAttribute("schoolList", schoolList);
            request.setAttribute("orderId", orderId);
            request.getRequestDispatcher(view).forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Usubmit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Usubmit.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void doIndex() {
        try {
            checkLogIn();
            List<SchoolEntity> schoolList = beanFactory.getSchoolBean().list();
            request.setAttribute("schoolList", schoolList);
            request.getRequestDispatcher(view).forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Usubmit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Usubmit.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
